<template>
  <div class="m-cart">
    <div class="m-cart-header">
      <div class="m-left"><h2 class="m-title">购物车</h2></div>
      <div class="m-right"><span class="m-clear" @click="_clearCart">清空购物车</span></div>
    </div>
    <transition name="cart-hide" v-on:before-enter="hideBeforeEnter" v-on:enter="hideEnter" v-on:leave="hideLeave">
      <div class="m-cart-content" ref="cartContent" v-show="cartShow">
        <ul class="m-foods">
          <li class="m-food" v-if="food.count > 0" v-for="(food, index) in foods" :key="index">
            <div class="img-wrapper"><img class="food-img" :src="food.imgSrc" alt="" /></div>
            <div class="info-wrapper">
              <h3 class="food-name">{{ food.name }}</h3>
              <p class="food-price">￥{{ food.price }}</p>
            </div>
            <div class="food-control"><Ball :food="food"></Ball></div>
          </li>
        </ul>
      </div>
    </transition>
    <div class="m-cart-footer">
      <div class="cart-img" @click="_cartShow"><span ref="icon-cart" class="iconfont icon-cart">&#xe6ab;</span></div>
      <div class="cart-info" @click="_cartShow">
        <p class="info" v-show="totalPrice > 0">总计:{{ totalPrice }}元</p>
      </div>
      <div class="cart-pay" @click="_order">
        <p class="text" :class="{ active: shop.pre_price < totalPrice }">{{ pay }}</p>
      </div>
    </div>
    <div class="balls">
      <transition-group name="drop" tag="div" v-on:before-enter="beforeEnter" v-on:enter="dropEnter" v-on:after-enter="afterEnter">
        <div class="ball" v-for="ball in balls" :key="ball.key" v-show="ball.show"><div class="inner inner-hook"></div></div>
      </transition-group>
    </div>
  </div>
</template>

<script>
import Ball from '@/components/shop/ball/ball.vue';
import Velocity from 'velocity-animate';

export default {
  data() {
    return {
      balls: [{ show: false, key: 1 }, { show: false, key: 2 }, { show: false, key: 3 }, { show: false, key: 4 }, { show: false, key: 5 }],
      fold: false,
      contentHeight: 0,
      dropBalls: []
    };
  },
  props: {
    // 比原有的商品属性多了一个 count 属性
    foods: {
      type: Array,
      default() {
        return [];
      }
    },
    shop: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  methods: {
    _clearCart() {
      this.foods.forEach(food => {
        food.count = 0;
      });
    },
    _cartShow() {
      this.fold = !this.fold;
    },
    _order() {
      let totalPrice = this.totalPrice;
      alert(`总结:${totalPrice}元`);
    },
    // 通过js控制样式
    hideBeforeEnter(el) {
      el.style.height = 0;
    },
    hideEnter(el, done) {
      Velocity(el, { height: this.contentHeight + 'px' }, { duration: 500 }, { complete: done });
    },
    hideLeave(el, done) {
      Velocity(el, { height: 0 }, { duration: 500 }, { complete: done });
    },
    drop(el) {
      // 获取balls中的小球，如果show=false则执行该小球的动画，同时将小球加入已经执行动画的小球集合中
      for (let i = 0; i < this.balls.length; i++) {
        let ball = this.balls[i];
        if (!ball.show) {
          ball.show = true;
          ball.el = el; // 绑定点击对象,为了获取点击对象的坐标作为小球动画的起始坐标
          this.dropBalls.push(ball);
          return;
        }
      }
    },
    beforeEnter(el) {
      let count = this.balls.length;
      while (count--) {
        let ball = this.balls[count];
        if (ball.show) {
          let rect = ball.el.getBoundingClientRect();
          let ballEl = this.$refs['icon-cart'].getBoundingClientRect();
          let x = rect.left - ballEl.left;
          let y = rect.top - ballEl.top;
          console.log(x, '==', y);
          el.style.display = '';
          el.style.transform = `translate3d(0,${y}px,0)`;
          el.style.webkitTransform = `translate3d(0,${y}px,0)`;
          let inner = el.getElementsByClassName('inner-hook')[0];
          inner.style.webkitTransform = `translate3d(${x}px,0,0)`;
          inner.style.transform = `translate3d(${x}px,0,0)`;
        }
      }
    },
    dropEnter(el, done) {
      /* eslint-disable no-unused-vars */
      /* 触发浏览器重绘; */
      let rf = el.offsetHeight;
      this.$nextTick(() => {
        el.style.webkitTransform = 'translate3d(0, 0, 0)';
        el.style.transform = 'translate3d(0, 0, 0)';
        let inner = el.getElementsByClassName('inner-hook')[0];
        inner.style.webkitTransform = 'translate3d(0, 0, 0)';
        inner.style.transform = 'translate3d(0, 0, 0)';
        el.addEventListener('transitionend', done);
      });
    },
    afterEnter(el) {
      el.style.display = 'none';
      let ball = this.dropBalls.shift();
      ball.show = false;
      ball.el = null;
    }
  },
  computed: {
    totalCount() {
      let totalCount = 0;
      this.foods.forEach(food => {
        if (food.count > 0) {
          totalCount += food.count;
        }
      });
      return totalCount;
    },
    totalPrice() {
      let totalPrice = 0;
      this.foods.forEach(food => {
        if (food.count > 0) {
          totalPrice += food.count * food.price;
        }
      });
      return totalPrice;
    },
    pay() {
      let totalPrice = 0;
      this.foods.forEach(food => {
        if (food.count > 0) {
          totalPrice += food.count * food.price;
        }
      });
      let diff = this.shop.pre_price - totalPrice;
      if (diff > 0) {
        return `差${diff}元起送`;
      } else {
        return '结算';
      }
    },
    cartShow() {
      if (!this.totalCount) {
        return false;
      }
      let show = !this.fold;
      return show;
    }
  },
  watch: {
    totalCount() {
      let count = 0;
      let contentHeight = 0;
      this.foods.forEach(food => {
        if (food.count > 0) {
          count += 1;
        }
      });
      if (contentHeight < 300 - 71) {
        contentHeight = count * 71;
      }
      if (!this.fold) {
        Velocity(this.$refs.cartContent, { height: contentHeight + 'px' }, { duration: 300 });
      }
      this.contentHeight = contentHeight;
    }
  },
  components: {
    Ball
  }
};
</script>
<style lang="stylus" rel="stylussheet/stylus">
@font-face
  font-family 'iconfont' /* project id 1536798 */
  src url('//at.alicdn.com/t/font_1536798_7xjersfdvx.eot')
  src url('//at.alicdn.com/t/font_1536798_7xjersfdvx.eot?#iefix') format('embedded-opentype'), url('//at.alicdn.com/t/font_1536798_7xjersfdvx.woff2') format('woff2'), url('//at.alicdn.com/t/font_1536798_7xjersfdvx.woff') format('woff'), url('//at.alicdn.com/t/font_1536798_7xjersfdvx.ttf') format('truetype'), url('//at.alicdn.com/t/font_1536798_7xjersfdvx.svg#iconfont') format('svg')
.iconfont
  font-family 'iconfont' !important
  font-size 16px
  font-style normal
  -webkit-font-smoothing antialiased
  -webkit-text-stroke-width 0.2px
  -moz-osx-font-smoothing grayscale
.m-cart
  width 100%
  border-radius 4px 4px 0 0
  background-color #fff
  .m-cart-header
    display flex
    width 100%
    height 45px
    line-height 45px
    font-size 16px
    box-sizing border-box
    padding 0 20px
    border-bottom 1px solid rgba(7, 17, 27, 0.2)
    background-color #fffdf0
    border-radius 4px 4px 0 0
    .m-left
      flex 1
      text-align left
    .m-right
      flex 1
      text-align right
      .m-clear
        cursor pointer
  .m-cart-content
    display flex
    max-height 500px
    overflow-y scroll
    padding 0 8px
    .m-foods
      width 100%
      .m-food
        border-bottom 1px solid rgba(7, 17, 27, 0.2)
        padding 5px 0
        display flex
        .img-wrapper
          flex 0 0 50px
          width 50px
          height 50px
          padding 5px
          font-size 0
          .food-img
            width 40px
            height 40px
        .info-wrapper
          flex 0 0 140px
          width 140px
          .food-name
            font-size 14px
            height 25px
            line-height 25px
            overflow hidden
            width 140px
            text-overflow ellipsis
          .food-price
            font-size 14px
            height 25px
            line-height 25px
            font-weight 700
            color red
        .food-control
          flex 1
          text-align right
  .m-cart-footer
    width 100%
    display flex
    height 50px
    background-color #333
    color #fff
    cursor pointer
    .cart-img
      flex 0 0 50px
      width 50px
      line-height 50px
      text-align center
      .icon-cart
        font-size 30px
    .cart-info
      flex 0 0 150px
      width 150px
      > .info
        height 50px
        line-height 50px
        padding-left 10px
    .cart-pay
      flex 1
      background-color #a0a0a0
      color #fff
      .text
        height 50px
        line-height 50px
        font-size 16px
        text-align center
        &.active
          background-color #ffd161
          color #333
          font-weight 700
  .balls
    .ball
      position absolute
      right 285px
      bottom 21px
      z-index 200
      &.drop-enter-active
        transition all 0.4s cubic-bezier(0.49, -0.29, 0.75, 0.41)
      .inner
        width 16px
        height 16px
        border-radius 50%
        background-color #333
        transition all 0.4s linear
</style>
